package org.example.util;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import org.junit.Test;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {
    private static volatile DataSource DS = null;
    private static DataSource gerDataSource() {
        if(DS == null) {
            synchronized (DBUtil.class) {
                if(DS == null) {
                    MysqlDataSource ds = new MysqlDataSource();
                    ds.setURL("jdbc:mysql://localhost:3306/image_system");
                    ds.setUser("root");
                    ds.setPassword("123456");
                    ds.setUseSSL(false);
                    ds.setCharacterEncoding("utf8");
                    DS = ds;
                }
            }
        }
        return DS;
    }

    public static Connection getConnection() {
        try {
            return gerDataSource().getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("获取数据库连接失败!<检查url，密码账号>",e);
        }
    }

    //释放资源 * 释放资源的重载方法：
    public static void close(Connection c, Statement s, ResultSet rs){
        try {
            if(rs != null) rs.close();
            if(s != null) s.close();
            if(c != null) c.close();
        } catch (SQLException e) {
            throw new RuntimeException("数据库释放资源出错",e);
        }
    }
    public static void close(Connection c,Statement s) {
        close(c,s,null);
    }

    @Test
    public void textGetConnection() {
        System.out.println(getConnection());
    }
}
